<template>
  <div>
    <a-row type="flex" justify="start">
      <a-col :span="4">
        <u-button type="primary" icon="btn-add" @click="add">
          新增组织
        </u-button>
      </a-col>
    </a-row>
    <a-table
      :columns="columns"
      :data-source="data"
      rowKey="organizationId"
      size="small"
      :expandIconColumnIndex="0"
      :pagination="false"
      :loading="loading"
      style="margin-top: 10px"
    >
      <span slot="description" slot-scope="description">
        {{ description || "-" }}
      </span>
      <span slot="action" slot-scope="text">
        <div class="flex">
          <div class="mr-10" @click="parentAdd(text)">
            <a-icon class="button-icon" type="plus" style="color: #1890ff" />
            <span class="button-text">新增</span>
          </div>
          <div class="mr-10" @click="edit(text)">
            <a-icon class="button-icon" type="edit" style="color: #1890ff" />
            <span class="button-text">编辑</span>
          </div>
          <div style="width: 90px" @click="onRemove(text)">
            <a-icon class="button-icon" type="delete" style="color: #1890ff" />
            <span class="button-text">删除</span>
          </div>
        </div>
      </span>
    </a-table>
    <a-modal
      :maskClosable="false"
      :keyboard="false"
      :title="title"
      :visible="visible"
      :footer="null"
      centered
      :width="600"
      @cancel="visible = false"
    >
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        labelAlign="left"
        layout="horizontal"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-form-model-item
          label="名称:"
          prop="organizationName"
          style="width: 100%"
        >
          <a-input
            v-model="form.organizationName"
            :max-length="32"
            placeholder="组织的名称，不可重复，最多输入32个字符"
            :disabled="lookDetail"
          />
        </a-form-model-item>
        <a-form-model-item
          label="上级组织:"
          prop="parentOrganizationId"
          style="width: 100%"
        >
          <a-tree-select
            v-model="form.parentOrganizationId"
            style="width: 100%"
            :disabled="lookDetail"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择组织"
            :treeDefaultExpandAll="false"
            :replaceFields="{
              children: 'children',
              title: 'organizationName', //  == 下拉框显示值 ==
              value: 'organizationId',
              key: 'organizationId',
            }"
            allow-clear
            tree-default-expand-all
            :tree-data="formTree"
          >
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="描述:" prop="description" style="width: 100%">
          <w-textarea
            v-model="form.description"
            :auto-size="{ minRows: 5, maxRows: 5 }"
            placeholder=""
            :maxLength="255"
            :disabled="lookDetail"
          />
        </a-form-model-item>
      </a-form-model>
      <div class="flex flex-end mt-10">
        <u-button
          type="default"
          style="font-weight: bold"
          @click="visible = false"
          >取消</u-button
        >
        <u-button class="ml-10 btn-default btn-confirm" @click="confirm">
          确定
        </u-button>
      </div>
    </a-modal>
  </div>
</template>
<script>
const columns = [
  {
    title: "组织名称",
    key: "organizationName",
    dataIndex: "organizationName",
  },
  {
    title: "描述",
    dataIndex: "description",
    key: "description",
    scopedSlots: { customRender: "description" },
  },
  {
    title: "创建时间",
    key: "createdTime",
    dataIndex: "createdTime",
    width: 160,
  },
  {
    title: "操作",
    key: "action",
    width: 220,
    scopedSlots: { customRender: "action" },
  },
];
import {
  deleteOrganization,
  addSystemOrganization,
  getOrganizationTree,
  updateSystemOrganization,
} from "@/api/organization";
import WTextarea from "@/components/WTextarea.vue";
export default {
  components: {
    WTextarea,
  },
  data() {
    return {
      data: [],
      columns,
      loading: false,
      title: "新增组织",
      visible: false,
      organizationId: null,
      form: {
        organizationName: null,
        parentOrganizationId: undefined,
        description: null,
      },
      rules: {
        organizationName: [
          { required: true, message: "组织名称不能为空", trigger: "change" },
        ],
      },
      formTreeData: [],
      lookDetail: false,
      treeDefaultExpandedKeys: [],
    };
  },
  computed: {
    formTree() {
      // 过滤掉当前节点及其子节点
      const filterData = (data, organizationId) => {
        return data.filter((item) => {
          if (item.organizationId === organizationId) {
            return false;
          } else if (item.children && item.children.length) {
            item.children = filterData(item.children, organizationId);
          }
          return true;
        });
      };
      return filterData(this.formTreeData, this.organizationId);
    },
  },
  mounted() {
    this.search();
  },
  methods: {
    async search() {
      this.loading = true;
      this.organizationId = null;
      await this.getList();
      await this.getFormTree();
      this.loading = false;
    },
    parentAdd(text) {
      this.title = "新增组织";
      console.log(text, "text");

      this.form = {
        organizationName: null,
        parentOrganizationId: text.organizationId || undefined,
        description: null,
      };
      this.visible = true;
      this.lookDetail = false;
    },
    add() {
      this.title = "新增组织";

      // this.$nextTick(() => {
      //   this.$refs.ruleForm.resetFields();
      // });
      this.form = {
        organizationName: null,
        parentOrganizationId: undefined,
        description: null,
      };
      this.visible = true;
      this.lookDetail = false;
      this.organizationId = null;
    },
    edit(text) {
      this.title = "编辑组织";
      this.visible = true;
      this.lookDetail = false;
      this.organizationId = text.organizationId;
      this.form.organizationName = text.organizationName;
      this.form.description = text.description;
      this.form.parentOrganizationId = text.parentOrganizationId || undefined;
      // this.form.parentOrganizationId = text.parentOrganizationId ? [text.parentOrganizationId] : [];
    },
    confirm() {
      if (!this.lookDetail) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.organizationId) {
              updateSystemOrganization({
                ...this.form,
                organizationId: this.organizationId,
              }).then(() => {
                this.$message.success("编辑成功");
                this.search();
                this.visible = false;
              });
            } else {
              const form = this.form;
              addSystemOrganization({
                organizationName: form.organizationName,
                description: form.description,
                parentOrganizationId: form.parentOrganizationId,
              }).then(() => {
                this.$message.success("新增成功");
                this.search();
                this.visible = false;
              });
            }
          } else {
            return false;
          }
        });
      } else {
        this.visible = false;
      }
    },
    getList() {
      getOrganizationTree({ paramType: 1 }).then((res) => {
        this.data = res.data;
      });
    },
    getFormTree() {
      getOrganizationTree({ paramType: 1 }).then((res) => {
        this.formTreeData =
          JSON.parse(JSON.stringify(this.formatData(res.data))) || [];
      });
    },
    // 格式化数据，递归将空的children置为undefined
    formatData(data) {
      const that = this;
      data.forEach((element) => {
        if (element.children && element.children.length > 0) {
          that.formatData(element.children);
        } else {
          element.children = undefined;
        }
      });
      return data;
    },
    // 删除
    onRemove(text) {
      const _this = this;
      this.$confirm({
        title: `提示`,
        content: `此操作将永久删除该数据，是否继续？`,
        onOk() {
          deleteOrganization(text.organizationId).then(() => {
            _this.$message.success("已删除");
            _this.search();
          });
        },
        onCancel() {
          _this.$message.info("已取消删除");
        },
      });
    },

    expandIcon(props) {
      if (props.record.children?.length) {
        if (props.expanded) {
          return (
            <a
              style="color: black; font-size:12px;margin-right:6px;"
              onClick={(e) => {
                props.onExpand(props.record, e);
              }}
            >
              <a-icon type="up" />
            </a>
          );
        } else {
          return (
            <a
              style="color: black;font-size:12px;margin-right:6px;"
              onClick={(e) => {
                props.onExpand(props.record, e);
              }}
            >
              <a-icon type="down" />
            </a>
          );
        }
      } else {
        //无数据-图标
        //这里我选择的是没有的话就不渲染
        return (
          <a style="color: black; font-size:12px;margin-right:6px;">
            <a-icon type="minus" />
          </a>
        );
      }
    },
  },
};
</script>
